import {getRequest} from "./api";

export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        router;
    }
    getRequest('/menu/listByAdminId').then(data => {
        if (data) {
            //格式化Router
            let fmtRoutes = formatRoutes(data.data);
            //添加到router 路由
            fmtRoutes.forEach(fmtRoute=>{
                router.addRoute(fmtRoute);
            })
           // router.addRoutes(fmtRoutes);
            //将数据存入vuex
            store.commit('initRoures', fmtRoutes);
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    console.log(routes);
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            iconCls,
            children
        } = router;
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        let fmtRoute = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            component(resolve) {
                if (component.startWith('Sys')){
                    require(['../views/sys/' + component + ".Vue"], resolve);
                }
            }
        }
        fmtRoutes.push(fmtRoute);
    });
    return fmtRoutes;
}